package com.gitee.urick.union.api.union.handler.v1;


import com.alibaba.fastjson.JSON;
import com.gitee.urick.union.api.union.IHandler;
import com.gitee.urick.union.api.union.dto.ReqCtx;
import com.gitee.urick.union.api.union.dto.base.BaseReq;
import com.gitee.urick.union.api.union.dto.base.BaseRes;
import com.gitee.urick.union.utils.TipsCode;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 修改记录
 * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * 修改日期				修改者						备注信息
 * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * 2020年08月25日			kkroc							初始化版本
 */
@Slf4j
public abstract class AbstractHandler<Req extends BaseReq, Res extends BaseRes> implements IHandler {
    private final Class<Req> reqType;
    private final Class<Res> resType;
    {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        reqType = (Class<Req>) params[0];
        resType = (Class<Res>) params[1];
    }

    public void beforeHandle(ReqCtx ctx) throws Exception {
        try {
            Req req = JSON.parseObject(ctx.getReqJson(), reqType);
            ctx.setReq(req);
            Res res = resType.newInstance();
            ctx.setRes(res);
        } catch (Exception e) {
            log.error("请求失败，初始化Handler：{}失败", getClass().getSimpleName());
            ctx.makeTips(TipsCode.Params_Failed);
        }
//        if(!(ctx.isTerminated()||ctx.isHandled())) { }
    }

    protected boolean isSign() {
        return true;
    }
}
